import ms from 'ms';
import { redis } from '@/redis';
import type { UserInfo } from '@/typings/user';

const getUserDataKey = (uid: string) => {
  return ['user', uid].join(':');
}

export class UserStore {
  static save = async (user: UserInfo) => {
    const key = getUserDataKey(user._id);
    const value = JSON.stringify(user);
    await redis.set(key, value, 'EX', ms('1 day') / 1000);
  }

  static get = async (uid: string) => {
    const key = getUserDataKey(uid);
    const res = await redis.get(key);
    const user = res ? JSON.parse(res) : null;
    return user as (UserInfo | null);
  }

  static update = (user: UserInfo) => {
    return this.save(user);
  }
}
